package com.fruitshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fruitshop.dto.UserLoginDTO;
import com.fruitshop.entity.User;
import com.fruitshop.exception.BusinessException;
import com.fruitshop.mapper.UserMapper;
import com.fruitshop.service.UserService;
import com.fruitshop.util.JwtUtil;
import com.fruitshop.util.WxUtil;
import com.fruitshop.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 用户服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    private final WxUtil wxUtil;
    private final JwtUtil jwtUtil;
    private final UserMapper userMapper;
    
    /**
     * 用户登录
     *
     * @param loginDTO 登录数据
     * @return 用户信息
     */
    @Override
    @Transactional
    public UserInfoVO login(UserLoginDTO loginDTO) {
        // 完全模拟登录，不依赖数据库
        log.info("模拟登录，接收参数: {}", loginDTO);
        
        // 构造模拟用户信息
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(1L);
        userInfoVO.setNickname(loginDTO.getNickname() != null ? loginDTO.getNickname() : "模拟用户");
        userInfoVO.setAvatarUrl(loginDTO.getAvatarUrl());
        userInfoVO.setGender(loginDTO.getGender() != null ? loginDTO.getGender() : 0);
        userInfoVO.setToken("mock_token_" + System.currentTimeMillis());
        
        return userInfoVO;
    }
    
    /**
     * 获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public UserInfoVO getUserInfo(Long userId) {
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(user.getId());
        userInfoVO.setNickname(user.getNickname());
        userInfoVO.setAvatarUrl(user.getAvatarUrl());
        userInfoVO.setGender(user.getGender());
        userInfoVO.setPhone(user.getPhone());
        userInfoVO.setEmail(user.getEmail());
        userInfoVO.setIs_vip(user.getIsVip());
        
        return userInfoVO;
    }
    
    /**
     * 更新用户手机号
     *
     * @param userId 用户ID
     * @param phone  手机号
     * @return 更新后的用户信息
     */
    @Override
    @Transactional
    public UserInfoVO updatePhone(Long userId, String phone) {
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPhone(phone);
        updateUser.setUpdateTime(LocalDateTime.now());
        
        updateById(updateUser);
        
        // 返回更新后的用户信息
        return getUserInfo(userId);
    }
    
    /**
     * 微信登录
     *
     * @param openid 微信用户唯一标识
     * @return 用户信息
     */
    @Override
    @Transactional
    public UserInfoVO loginByWechat(String openid) {
        // 根据openid查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenid, openid);
        User user = userMapper.selectOne(wrapper);
        
        // 用户不存在则注册新用户
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setNickname("微信用户");
            user.setStatus(0); // 正常状态
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setDeleted(0); // 未删除
            
            userMapper.insert(user);
            log.info("新微信用户注册成功: {}", user);
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getId());
        
        // 组装返回数据
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(user.getId());
        userInfoVO.setNickname(user.getNickname());
        userInfoVO.setAvatarUrl(user.getAvatarUrl());
        userInfoVO.setGender(user.getGender());
        userInfoVO.setPhone(user.getPhone());
        userInfoVO.setToken(token);
        
        return userInfoVO;
    }

    @Override
    @Transactional
    public UserInfoVO loginByWechatPhone(String openid, String phoneNumber) {
        // 根据openid查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenid, openid);
        User user = userMapper.selectOne(wrapper);
        
        // 用户不存在则注册新用户
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setNickname("微信用户");
            user.setPhone(phoneNumber);
            user.setStatus(0); // 正常状态
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setDeleted(0); // 未删除
            user.setIsVip(0); // 默认非VIP
            
            userMapper.insert(user);
            log.info("新微信用户注册成功: {}", user);
        } else {
            // 更新用户手机号
            user.setPhone(phoneNumber);
            user.setUpdateTime(LocalDateTime.now());
            userMapper.updateById(user);
            log.info("更新用户手机号成功: {}", user);
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getId());
        
        // 组装返回数据
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(user.getId());
        userInfoVO.setNickname(user.getNickname());
        userInfoVO.setAvatarUrl(user.getAvatarUrl());
        userInfoVO.setGender(user.getGender());
        userInfoVO.setPhone(user.getPhone());
        userInfoVO.setToken(token);
        
        return userInfoVO;
    }

    @Override
    @Transactional
    public UserInfoVO saveMockUser(UserInfoVO userInfo) {
        // 检查是否已存在模拟用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, userInfo.getId());
        User existingUser = userMapper.selectOne(wrapper);
        
        if (existingUser == null) {
            // 创建新用户
            User user = new User();
            user.setId(userInfo.getId());
            user.setNickname(userInfo.getNickname());
            user.setAvatarUrl(userInfo.getAvatarUrl());
            user.setGender(userInfo.getGender());
            user.setPhone(userInfo.getPhone());
            user.setEmail(userInfo.getEmail());
            user.setStatus(0); // 正常状态
            user.setIsVip(userInfo.getIs_vip());
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setDeleted(0); // 未删除
            
            userMapper.insert(user);
            log.info("新模拟用户注册成功: {}", user);
        } else {
            // 更新现有用户
            existingUser.setNickname(userInfo.getNickname());
            existingUser.setAvatarUrl(userInfo.getAvatarUrl());
            existingUser.setGender(userInfo.getGender());
            existingUser.setPhone(userInfo.getPhone());
            existingUser.setEmail(userInfo.getEmail());
            existingUser.setIsVip(userInfo.getIs_vip());
            existingUser.setUpdateTime(LocalDateTime.now());
            
            userMapper.updateById(existingUser);
            log.info("更新模拟用户成功: {}", existingUser);
        }
        
        return userInfo;
    }
} 